package com.blog.controller;

import com.alibaba.fastjson.JSONObject;
import com.blog.pojo.IdentifyCode;
import com.blog.pojo.User;
import com.blog.service.UserService;
import com.blog.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * Copyright (C), 2022
 * Author: 苏大大
 * Date: 2022-04-15 16:03
 * FileName: UserController
 * Description:
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController extends BaseController{
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, java.io.Serializable> redisTemplate;

    /***
     * 用户登录
     * @param session
     * @param account
     * @param password
     * @return
     */
    @PostMapping("/login/{account}/{password}/{VerifyCode}")
    public String login( @PathVariable("account") String account, @PathVariable("password") String password,@PathVariable("VerifyCode") String VerifyCode ,HttpSession session){
        log.info("用户验证登录:{}",account);
        log.info("图形验证码为:{}",redisTemplate.opsForValue().get("VerifyCode"));
        JSONObject object=new JSONObject();
        //获取redis图形验证码缓存
        String codeNext= Objects.requireNonNull(redisTemplate.opsForValue().get("VerifyCode")).toString();
        System.out.println(codeNext);
        //图形验证码验证
        if(!codeNext.equals(VerifyCode.toUpperCase())){
            log.info("图形验证码错误,返回错误信息");
            object.put("message","图片验证码错误!");
            object.put("flag",false);
            return  object.toJSONString();
        }
        User user=userService.Login(account,password);
        if(user==null){
            log.info("用户登录验证失败");
            object.put("message","登录失败,账号或密码错误!");
            object.put("flag",false);
            return object.toJSONString();
        }else{
            log.info("登录验证成功,用户ID传入会话");
            log.info("SessionId为{}",session.getId());
            session.setMaxInactiveInterval(30);
            //异常设备的json数组,把list转换为json形式数组
            JSONObject jsonObject= JSONObject.parseObject(JSONObject.toJSONString(user));
            //将json形式数组装换为string类型
            String json= jsonObject.toJSONString();
            //将需要缓存的数据缓存入redis
            redisTemplate.opsForValue().set(user.getUid()+"",json);
            object.put("user",user);
            object.put("flag",true);
        }
        return object.toJSONString();
    }

    /***
     * 用户退出登录
     * @return
     */
    @GetMapping("/quit/{uid}")
    public String Userquit(@Param("用户ID")  @PathVariable("uid") Long uid){
        JSONObject object=new JSONObject();
        if(logout(uid)){
            object.put("flag",true);
            return object.toJSONString();
        }
        object.put("flag",false);
        return object.toJSONString();
    }

    /***
     * 用户注册
     * @param
     * @return
     */
    @PostMapping("/register/{username}/{password}/{avatar}/{phone}")
    public String register(@PathVariable("username") String username, @PathVariable("password")String password,@PathVariable("avatar") String avatar,@PathVariable("phone") String phone){
        User user=new User();
        user.setUid(UUIDUtils.getNumber()).setUsername(username).setPassword(password).setAvatar(avatar).setPhone(phone);
        JSONObject object =new JSONObject();
        log.info("用户{}开始注册",user.getUsername());
        //设置为默认头像
        user.setAvatar("http://localhost:8001/img/user/avatar/acquiescent.png");
        if(userService.register(user)==0){
            log.info("用户注册失败!");
            object.put("success",false);
        }else{
            log.info("用户注册成功,用户名为:{}   Uid为:{}",user.getUsername(),user.getUid());
            object.put("flag",true);
        }
        return object.toJSONString();
    };
    //根据用户id查询用户信息
    @GetMapping("/getUser/{uid}")
    public String getUser(@PathVariable("uid") Long uid){
        JSONObject object=new JSONObject();
        if(uid!=null){
            User user=userService.getUser(uid);
            System.out.println(user);
            object.put("User",user);
            object.put("flag",true);
            return object.toJSONString();
        }
        object.put("flag",false);
        return object.toJSONString();
    }

    /***
     * 用户注册短信验证
     * @param phone
     * @return
     */
    @PostMapping("/SendMessage/{phone}")
    public String sendMessage(@PathVariable("phone") String phone){
        JSONObject object=new JSONObject();
      String msage =MessAgeAuThenTiCationCodeUtils.sendMessage(phone);
      if(msage.equals("0")){
            object.put("flag",false);
            log.info("短信验证码发送失败!");
            object.put("error","短信验证码发送失败");
      }else{
          object.put("flag",true);
          log.info("短信发送成功,向前端发送短信验证码进行校验");
          object.put("phone",msage);
      }
      return object.toJSONString();
    }

    /***
     * 修改用户信息
     * @param session
     * @return
     */
    @PutMapping("/update")
    public String updateById(HttpSession session,@RequestBody User user){
        JSONObject object=new JSONObject();
        if (user.getUid() != null) {
            User user1=userService.queryById(user.getUid());
            if(user.getPassword().isEmpty()){
                user.setPassword(user1.getPassword());
            }
            if(user.getAvatar().equals(user1.getAvatar())&&user.getPassword().equals(user1.getPassword())&&user.getUsername().equals(user1.getUsername())){
                object.put("flag",false);
                object.put("message","账号信息无任何修改!");
                return object.toJSONString();
            }
            //获取当前时间并修改对象的修改时间
            LocalDateTime localDateTime=LocalDateTime.now();
            user.setUpdateTime(localDateTime);
            object.put("flag",userService.update(user)==1);
        }else{
            object.put("flag",false);
            return object.toJSONString();
        }
        log.info("修改用户信息:用户ID为:{}",user.getUid());
        return object.toJSONString();
    }

    /***
     * 用户修改头像
     * @param file
     * @param session
     * @return
     * @throws IOException
     */
    @PostMapping("/updateAvatar/{uid}")
    public String updateAvatarById(MultipartFile file, HttpSession session,@PathVariable("uid") Long uid) throws IOException {
       JSONObject object= new JSONObject() ;
         log.info( "检查用户是否登录");
        User user=checkUser(uid);
        if (user != null) {
            log.info("获取用户信息,用户id为{}",user.getUid());
        }else{
            object.put("flag",false);
            return object.toJSONString();
        }
      if(user.getAvatar().equals("acquiescent.png")){
          //上传头像
      }else{
          //删除上次头像
      }
        //判断是否上传了头像
      String filepath=AvatarUtils.uploadAvatar(file);

      object.put("fileName",filepath);
      object.put("flag",true);
      return object.toJSONString();
    }
    /***
     * 测试RedisHttpSession共享
     * @param request
     * @return
     */
    @GetMapping("/getuid")
    public String getSessionuid(HttpServletRequest request){
        HttpSession session = request.getSession();
        return session.getId();
    }

    @GetMapping(value = "/generate")
    public String generateIdentifyCode(HttpServletRequest request, HttpServletResponse response,
                                       @RequestParam(value = "width", required = false, defaultValue = "100") int width,
                                       @RequestParam(value = "height", required = false, defaultValue = "30") int height) {

        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        //生成图片上的文字
        IdentifyCode code = IdentIfyingCode.generateIdentifyCode(request, width, height);
        String uniqueId = (String) code.getUniqueId();
        JSONObject object=new JSONObject();
        object.put("VerifyCode",code.getCapText());
        //保存验证码到cookie
        Cookie cookie = new Cookie("_UNIQUE_ID", uniqueId);
        //利用JSONObject将图片验证码转化为json形式保存
        JSONObject  jsonObject = JSONObject.parseObject(object.toJSONString());
        String json=jsonObject.toJSONString();

        //利用redis缓存存取图片验证码
        redisTemplate.opsForValue().set("VerifyCode",code.getCapText());
        //60s过期
        cookie.setMaxAge(120);
        cookie.setPath("/");
        response.addCookie(cookie);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write((BufferedImage) code.getImg(), "jpg", out);
            // 强制将缓冲区所有的数据输出！
            out.flush();
        } catch (IOException e) {
            // ApiLogger.error("generate identify code is error, e " + e);
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                // ApiLogger.error("generate identify code, close out is error, e " + e);
            }
        }
        return object.toJSONString();
    }

    /***
     * 注册时查询用户名是否已被占用
     * @param username
     * @return
     */
    @GetMapping("/queryname/{username}")
    public String queryUserName(@PathVariable("username")String username){
        JSONObject object=new JSONObject();
        int flag=userService.queryUserName(username);
        object.put("flag",flag==0);
        return object.toJSONString();
    }

    /***
     * 注册时查询手机号是否已被占用
     * @param phone
     * @return
     */
    @GetMapping("/queryphone/{phone}")
    public String queryUserPhone(@PathVariable("phone")String phone){
        JSONObject object=new JSONObject();
        User user=userService.queryUserPhone(phone);
        object.put("flag",user==null);
        object.put("user",user);
        return object.toJSONString();
    }

    @GetMapping("/getAvatar")
    public String getAvatar(){
       List<String> list= userService.queryAvatarAll();
       JSONObject object=new JSONObject();
       object.put("list",list);
       return object.toJSONString();
    }
}
